//  头部点击时下划线变化
const clear_section = function () {
    $('.form-section').empty()
};

const SUCCESS_COLOR = '#2ecc71'

const login_page = function () {
    $('.form-section').html("<div class=\"login-password\">\n" +
        "            <ul>\n" +
        "                <li><input id=\"login_account\" class=\"inp\" type=\"text\" placeholder=\"请输入邮箱或账号\" maxlength='40'></li>\n" +
        "                <li><input id=\"login_password\" class=\"inp\" type=\"password\" placeholder=\"请输入密码\" maxlength='20'></li>\n" +
        "                <li><a id=\"forget_password\" href=\"#\">忘记密码</a></li>\n" +
        "                <li><input id=\"login_btn\" type=\"button\" class=\"btn btn-primary\" value=\"登录\"></li>\n" +
        "            </ul>\n" +
        "        </div>\n" +
        "\n" +
        "        <div class=\"form-message\">—————— 其他方式登录 ——————</div>\n" +
        "        <div class=\"login-others\">\n" +
        "            <span class=\"login-wechat\">\n" +
        "                <img src='../image/icon_wechat.png' alt=\"\">\n" +
        "            </span>\n" +
        "            <span class=\"login-qq\">\n" +
        "                <img src='../image/icon_QQ.png' alt=\"\">\n" +
        "            </span>\n" +
        "        </div>")
    $('.form-section .login-password').css({
        "top": "0"
    })
    $('.form-section #login_btn').css({
        "top": "18px"
    })

    $(document).ready(loginEvent)
};

// 注意，这里的注册按钮的id为login_btn
const register_page = function () {
    $('.form-section').html("<div class=\"login-password\">\n" +
        "      <ul>\n" +
        "        <li><input id=\"register_account\" class=\"inp\" type=\"text\" placeholder=\"请输入账号\" maxlength='15'></li>\n" +
        "        <li><input id=\"register_password\" class=\"inp\" type=\"password\" placeholder=\"请输入密码\" maxlength='20'></li>\n" +
        "        <li><input id=\"register_repassword\" class=\"inp\" type=\"password\" placeholder=\"请再次输入密码\" maxlength='20'></li>\n" +
        "        <li><input id=\"register_email\" class=\"inp\" type=\"text\" placeholder=\"请输入邮箱\" maxlength='40'></li>\n" +
        "        <li><input id=\"register_captcha\" class=\"inp\" type=\"text\" placeholder=\"请输入邮箱验证码\" maxlength='5'></li>\n" +
        "        <li><input id=\"login_btn\" type=\"button\" class=\"btn btn-primary\" value=\"注册\"></li>\n" +
        "        <li><p id=\"get_captcha\">获取验证码</p></li>\n" +
        "      </ul>\n" +
        "    </div>")
    $('.form-section .login-password').css({
        "top": "-20px"
    })

    $(document).ready(registerEvent)
};
$(document).ready(function () {
    // 生成登录界面
    login_page()
    $('#top_login_btn').click(function () {
        $('.form-top .form-underline').css({
            "left": "-45px",
        })
        clear_section()
        login_page()
    })
    $('#top_register_btn').click(function () {
        $('.form-top .form-underline').css({
            "left": "45px",
        })
        clear_section()
        register_page()
    })

})

function loginEvent() {
    let $loginAccount = $('#login_account'),
        $loginPassword = $('#login_password'),
        $loginBtn = $('#login_btn')


    $loginAccount.on('blur', function () {
        let account = $loginAccount.val()
        checkLoginAccount(account)
    })

    $loginPassword.on('blur', function () {
        let password = $loginPassword.val()
        checkPasswordFormat(password)
    })

    $loginBtn.on('click', function () {
        let account = $loginAccount.val(),
            password = $loginPassword.val()
        if (checkLoginAccount(account) && checkPasswordFormat(password)) {
            login(account, password)
        }
    })

}


function registerEvent() {
    let $registerAccount = $('#register_account'),
        $registerPassword = $('#register_password'),
        $registerRepassword = $('#register_repassword'),
        $registerEmail = $('#register_email'),
        $registerCaptcha = $('#register_captcha'),
        $registerBtn = $('#login_btn'),
        $getCaptcha = $('#get_captcha')

    $registerAccount.on('blur', function () {
        let account = $registerAccount.val()
        checkRegisterAccount(account)
    })

    $registerPassword.on('blur', function () {
        let password = $registerPassword.val(),
            repassword = $registerRepassword.val()
        checkPasswordFormat(password)
        checkPasswordSame(password, repassword)
    })
    $registerRepassword.on('blur', function () {
        let password = $registerPassword.val(),
            repassword = $registerRepassword.val()
        checkPasswordFormat(repassword)
        checkPasswordSame(password, repassword)
    })
    $registerEmail.on('blur', function () {
        checkEmailFormat($registerEmail.val())
    })

    $registerBtn.on('click', function () {
        if (checkRegisterAccount($registerAccount.val()) && checkPasswordFormat($registerPassword.val()) && checkPasswordSame($registerPassword.val(), $registerRepassword.val()) && checkEmailFormat($registerEmail.val())) {
            if (checkCaptcha($registerCaptcha.val())) {
                register($registerAccount.val(), $registerPassword.val(), $registerEmail.val(), $registerCaptcha.val())
            }
        }
    })

    $getCaptcha.on('click', function () {
        getCaptcha($registerEmail.val())
    })

}

//  登录请求
function login(account, password) {
    let $prompt = $('#error-prompt')
    const loginApi = '/session'
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({account, password})
    };
    // 发送账号密码登录请求
    fetch(loginApi, requestOptions)
        .then((response) => {
            if (!response.ok) {
                showFailPrompt($prompt, '登录失败')
            }
            return response.json()
        })
        .then((data) => {
            if (data) {
                showSuccessPrompt($prompt, '登录成功')
                // 延迟1s跳转到首页
                setTimeout(() => {
                    location.href = '/index'
                }, 1000)
            } else {
                showFailPrompt($prompt, '登录失败')
            }
        })
        .catch((error) => showFailPrompt($prompt, '登录失败,请稍后再试'));
}

//注册请求  先判断账号是否存在，再判断邮箱是否已经注册，再验证验证码是否正确 如果正确再发送注册请求
function register(account, password, email, captcha) {
    let $prompt = $('#error-prompt')
    const checkAccountApi = `/user/${account}/account`,
        checkEmailApi = `/user/${account}/email`,
        checkCaptchaApi = `/code/${email}/${captcha}`,
        registerApi = '/user'
    fetch(checkAccountApi)
        .then((response) => {
            if (!response.ok) {
                throw new Error('检查用户名失败');
            }
            return response.json();// 将返回的 JSON 数据解析为布尔值,下同
        })
        .then((isUsernameAvailable) => {
            if (!isUsernameAvailable) {
                showFailPrompt($prompt, '用户名已经被注册')
            }
            return fetch(checkEmailApi);// 如果用户名可用，则检查邮箱是否已经注册
        })
        .then((response) => {
            if (!response.ok) {
                throw new Error('检查邮箱失败');
            }
            return response.json();
        })
        .then((isEmailAvailable) => {
            if (!isEmailAvailable) {
                showFailPrompt($prompt, '邮箱已经被注册')
            }
            return fetch(checkCaptchaApi);// 如果邮箱可用，则验证验证码是否正确
        })
        .then((response) => {
            if (!response.ok) {
                throw new Error('验证验证码失败');
            }
            return response.json();
        })
        .then((isCaptchaValid) => {
            if (!isCaptchaValid) {
                showFailPrompt($prompt, '验证码错误')
            }
            const requestOptions = {// 如果验证码正确，则发送注册请求
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({account, email, password})
            };
            return fetch(registerApi, requestOptions);
        })
        .then((response) => {
            if (!response.ok) {
                showFailPrompt($prompt, '注册失败')
            }
            return response.json();
        })
        .then((data) => {
            if (data) {
                showSuccessPrompt($prompt, '注册成功')
                setTimeout(() => {
                    location.href = '/login'
                }, 1000)
            }else {
                showFailPrompt($prompt, '注册失败')
            }
        })
        .catch((error) => showFailPrompt($prompt, '注册失败,请稍后再试'));

}

//   获取验证码请求
function getCaptcha(email) {
    let $prompt = $('#error-prompt'),
        $getCaptcha = $('#get_captcha')

    let emailCaptchaApi = `/code/${email}`

    fetch(emailCaptchaApi)
        .then((response) => {
            if (!response.ok) {
                showFailPrompt($prompt, '验证码发送失败')
            }
        })
        .then((data) => {
            if (data) {
                showSuccessPrompt($prompt, '验证码发送成功')
                changeCaptchaStyle($getCaptcha)
            } else {
                showFailPrompt($prompt, '验证码发送失败')
            }
        })
        .catch((error) => showFailPrompt($prompt, '验证码发送失败,请稍后再试'));
}

function checkCaptcha(captcha) {
    let $prompt = $('#error-prompt')
    if (captcha.length === 5) {
        return true
    } else {
        showFailPrompt($prompt, '验证码格式错误')
        return false
    }
}

function checkPasswordSame(psw, re_psw) {
    let $prompt = $('#error-prompt')
    if (psw === re_psw) {
        return true
    } else {
        showFailPrompt($prompt, '两次密码不一致')
        return false
    }
}

function checkRegisterAccount(account) {
    let $prompt = $('#error-prompt')
    if (!checkAccount(account)) {
        showFailPrompt($prompt, "账号格式错误")
        return false
    }
    return true
}

function checkLoginAccount(account) {
    let $prompt = $('#error-prompt')
    if (checkAt(account)) {
        if (!checkEmailFormat(account)) {
            showFailPrompt($prompt, '邮箱格式错误')
            return false
        }
    } else {
        if (!checkAccount(account)) {
            showFailPrompt($prompt, '账号格式错误')
            return false
        }
    }
    return true
}


function checkPasswordFormat(password) {
    let $prompt = $('#error-prompt')
    console.log(checkPassword(password))
    if (!checkPassword(password)) {
        showFailPrompt($prompt, '密码格式错误')
        return false
    }
    return true
}

function changeCaptchaStyle($getCaptcha) {
    $getCaptcha.css('background-color', '#ccc')
    $getCaptcha.css('cursor', 'not-allowed')
    $getCaptcha.attr('disabled', true)
    //  解绑事件
    $getCaptcha.off('click')
    let time = 60
    let timer = setInterval(() => {
        if (time === 0) {
            clearInterval(timer)
            $getCaptcha.css('background-color', '#fff')
            $getCaptcha.css('cursor', 'pointer')
            $getCaptcha.attr('disabled', false)
            $getCaptcha.text('获取验证码')
            $getCaptcha.on('click', function () {
                getCaptcha($('#register_email').val())
            })
        } else {
            $getCaptcha.text(`${time}s后重新获取`)
            time--
        }
    }, 1000)
}

//  检测账号格式
function checkAccount(account) {
    let reg = /^\w{5,15}$/
    return reg.test(account)
}

//  检测邮箱格式
function checkEmailFormat(email) {
    let reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
    return reg.test(email)
}

//  检测是否存在@符号
function checkAt(email) {
    let reg = /@/
    return reg.test(email)
}

//  检测密码格式
function checkPassword(password) {
    let reg = /^\w{8,20}$/
    return reg.test(password)
}


function showSuccessPrompt($prompt, str) {
    showPrompt($prompt, str, SUCCESS_COLOR)
}

function showFailPrompt($prompt, str) {
    showPrompt($prompt, str)
}

function showPrompt($prompt, str, color = '#f1403c') {
    $prompt.text(str)

    let $box = $('.prompt-box')
    $box.css('background-color', color)
    $box.show()
    setTimeout(function () {
        $box.hide()
    }, 1200)
}


